//导入 jwt
const jwt = require('jsonwebtoken');
//读取配置项
const { secret } = require('../config/config');
//声明中间件
module.exports = (req, res, next) => {
  //判断
  let token = req.get('token');
  if (!token) {
    return res.json({
      code: '2003',
      msg: 'token缺失',
      data: null,
    });
  }
  //检验token
  jwt.verify(token, secret, (err, data) => {
    if (err) {
      return res.json({
        code: '2004',
        msg: 'token 验证失败',
        data: null,
      });
    }
    //保存用户的信息
    req.user = data;
    //如果检验超过
    next();
  });
};
